<script setup lang="ts">
import { dictionaryUpdateDataApi, dictionaryCreateApi } from "@/api/system/dict/index"
import { ElMessage } from 'element-plus'
import { useRequest } from "vue-hooks-plus"
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  id: {
    type: String,
    default: ''
  },
  name: {
    type: String,
    default: ''
  },
  curItem: {
    type: Object,
    default: ''
  },
  title: {
    type: String,
    default: ''
  }
})

const emits = defineEmits(['cancel'])

const formRef = ref()
const form = ref({
  name: props.name || '',
  dataName: props.curItem.name || '',
  dataRemark: props.curItem.dataRemark || ''
})

const rules = ref({
  name: [{ required: true, message: "字典名称不能为空", trigger: "blur" }],
  dataName: [{ required: true, message: "字典数据名称不能为空", trigger: "blur" }],
})

const { run: add, loading: addLoading } = useRequest(dictionaryCreateApi, {
  manual: true,
  onSuccess: () => {
    ElMessage({
      message: '新增成功',
      type: 'success',
    })
    emits('cancel', true)
  }
})

const { run: update, loading: updateLoading } = useRequest(dictionaryUpdateDataApi, {
  manual: true,
  onSuccess: () => {
    ElMessage({
      message: '编辑成功',
      type: 'success',
    })
    emits('cancel', true)
  }
})

const handleSubmit = () => {
  formRef.value.validate(valid => {
    if (valid) {
      if (props.id) {
        update({
          id: props.id,
          ...form.value
        })
      } else {
        add(form.value)
      }
    }
  })
}

</script>

<template>
  <div>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog v-model="props.visible" :title="props.title" width="600px" align-center @close="emits('cancel')">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="字典名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入字典名称" disabled />
        </el-form-item>
        <el-form-item label="字典数据名称" prop="dataName">
          <el-input v-model="form.dataName" placeholder="请输入字典数据名称" clearable :maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="备注" prop="dataRemark">
          <el-input v-model="form.dataRemark" type="textarea" placeholder="请输入内容" clearable :maxlength="200"
            show-word-limit />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="emits('cancel', false)">取消</el-button>
          <el-button type="primary" :loading="addLoading || updateLoading" @click="handleSubmit">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
:deep(.el-textarea__inner) {
  min-height: 136px !important;
}
</style>